<template>
  <div class="app-container clipdetail">
    <el-tabs v-model="listType" @tab-click="tabChange">
      <el-tab-pane name="1" label="素材列表"/>
      <el-tab-pane name="2" label="合辑列表"/>
    </el-tabs>
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
      <div v-show="listType == 1" class="filter-item">
        <el-select v-model="listQuery.status" placeholder="请选择剪辑状态" style="width:160px;">
          <el-option
            v-for="item in clipStatusFormat"
            :key="item.key"
            :label="item.value"
            :value="item.key"/>
        </el-select>
      </div>
      <div class="filter-item">
        <el-select v-model="listQuery.inStock" placeholder="请选择审核状态" style="width:160px;">
          <el-option
            v-for="item in audioStatusFormat"
            :key="item.key"
            :label="item.value"
            :value="item.key"/>
        </el-select>
      </div>
      <div class="buttonGroup">
        <el-button class="filter_button" icon="el-icon-search" @click="handleFilter">查找</el-button>
      </div>
    </div>
    <!-- 页面全局操作 -->
    <div class="buttons">
      <tagButton v-show="listType==1" size="big" name="创建合辑" @click="showDialog"/>
      <tagButton name="提交审核" size="big" @click="submitAudit(2)"/>
    </div>
    <!-- 查询结果 -->
    <MCTable v-show="listType==1" :data-source="materialSource" @handleSelectionChange="handleSelectionChange"/>
    <MCTable v-show="listType==2" :data-source="collectSource" @handleSelectionChange="handleSelectionChange"/>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="sizeChange" />
    <!-- 合辑弹窗 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="查看合辑"
      width="80%"
    >
      <div class="marginBottom10">
        <span class="marginRight10">合辑ID：{{ collectObj.id }}</span>
        <span>合辑名称：<el-input v-model="collectObj.name" style="width:150px;" placeholder="请输入内容"/></span>
      </div>
      <MCTable :data-source="collectDetailSource"/>
      <span slot="footer" class="dialog-footer">
        <el-button v-show="collectObj.canUpdate" type="primary" @click="createColl">{{ collectObj.isCreate?'创建':'修改' }}</el-button>
        <el-button type="primary" @click="dialogVisible=false,auditList=[]">{{ collectObj.isCreate?'取消':'关闭' }}</el-button>
      </span>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog
      :visible.sync="dialogView"
      :show-close="false"
      width="25%"
      title="预览"
      custom-class="views"
    >
      <div id="mainContainer" class="" style="width:95%;margin:auto;">
        <live-video-area-view
          v-if="video && video.sourceUrl"
          id="mainPlayer"
          ref="mainPlayer"
          :url="video.sourceUrl"
          style="width: 100%; height: 100%;"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureView">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import Pagination from '../../../components/Pagination'
import ObjectUtil from '../../../utils/object-util'
import { apiVideo as API } from '../../../api/clip/task'
import FileUploader from '../../../components/common/FileUploader'
import RadioMeterialClipResult from './clipResult'
import Fn from '../../../utils/fn'
import {
  clipStatusFormat,
  audioStatusFormat
} from '../../../mixin/MixinContants'
import { FileUtil } from '../../../utils/file-util'
import LiveVideoAreaView from './views/LiveVideoAreaView'
import Common from '../../../utils/common'
import tagButton from '../../../components/common/tagButton'
import { materialColumn, collectColumn, collectDetailColumn } from './clipColumns/materialColumns'

export default {
  name: 'RadioMeterialTaskList',
  components: { RadioMeterialClipResult, FileUploader, BackToTop, Pagination, LiveVideoAreaView, tagButton },
  mixins: [
    clipStatusFormat.mixin,
    audioStatusFormat.mixin
  ],
  data() {
    return {
      // 单个素材数据源
      materialSource: {
        headerLines: 3,
        list: [],
        columns: materialColumn,
        options: {
          mutiSelect: true
        },
        operates: {
          fixed: 'right',
          list: [
            { label: '预览', show: (row) => (row.status == 1),
              method: (index, row) => {
                this.views(row)
              }
            },
            { label: '提交审核',
              show: (row) => (
                (row.inStock == -1 || row.inStock == 2) && row.status == 1
              ),
              method: (index, row) => {
                this.submitAudit(1, row.id, row.taskId)
              }
            },
            { label: '修改',
              show: (row) => (
                (row.inStock != 1) && row.status != 0
              ),
              method: (index, row) => {
                this.handleEdit(row.taskId)
              }
            },
            { label: '删除', show: (row) => (true),
              method: (index, row) => {
                this.handleDel(row.id)
              }
            }
          ]
        }
      },
      // 合辑数据源
      collectSource: {
        headerLines: 3,
        list: [],
        columns: collectColumn,
        options: {
          mutiSelect: true
        },
        operates: {
          fixed: 'right',
          list: [
            { label: '查看合辑', show: (row) => (true),
              method: (index, row) => {
                this.viewCollect(row)
              }
            },
            { label: '取消合辑',
              show: (row) => (
                row.inStock == -1 || row.inStock == 2
              ),
              method: (index, row) => {
                this.delCollect(row.id)
              }
            }
          ]
        }
      },
      // 合辑详情数据源
      collectDetailSource: {
        list: [],
        columns: collectDetailColumn,
        options: { hasLoading: false },
        operates: {
          fixed: 'right',
          list: [
            { label: '预览', show: (row) => (true),
              method: (index, row) => {
                this.views(row)
              }
            },
            { label: '移除', show: (row) => (this.collectObj.isCreate === true),
              method: (index, row) => {
                this.handleDel(row.id)
              }
            },
            { label: '上移', show: (row) => (this.collectObj.isCreate === true),
              method: (index, row) => {
                this.upOrDown(index, 0)
              }
            },
            { label: '下移', show: (row) => (this.collectObj.isCreate === true),
              method: (index, row) => {
                this.upOrDown(index, 1)
              }
            }
          ]
        }
      },
      listType: '1',
      dialogVisible: false,
      dialogView: false,
      clipId: '',
      bind_title: '',
      present: 0,
      // total:0,
      allPage: 1,
      page: 1,
      total: 0,
      videotype: '',
      list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        clipType: 1,
        status: undefined,
        // auditStatus:undefined,
        inStock: undefined
        // sort: 'add_time',
        // order: 'desc'
      },
      dialogStatus: '',

      downloadLoading: false,
      taskId: '',
      taskTitle: '',
      video: { sourceUrl: undefined },
      // 合辑id
      collectionId: '',
      // 合辑名称
      collectionName: '',
      // 合辑信息
      collectObj: {
        id: undefined,
        name: undefined,
        isCreate: true,
        canUpdate: true
      },
      // 选择的提审的素材
      auditList: []
    }
  },
  created() {
    this.taskId = this.$route.query.id
    this.taskTitle = this.$route.query.title
    this.Init()
  },
  mounted() {
  },
  methods: {
    // 合辑详情
    async viewCollect({ id, inStock }) {
      this.collectObj.isCreate = false
      this.collectObj.canUpdate = (inStock == -1 || inStock == 2)
      const [err,res] = await this.$await(API.CollectDetail({ id }))
      if(!err){
        this.collectDetailSource.list = res.datas.clipList
        this.collectObj.id = res.datas.rdClipCol.id
        this.collectObj.name = res.datas.rdClipCol.name
        this.dialogVisible = true
      }
      
    },
    // 删除合辑
    delCollect: Fn.Confirm(async function(id) {
      const [err,res] = await this.$await(API.delCollect({ id }))
      if(!err){
        this.getList()
      }

    }),
    // 上移下移
    upOrDown(i, t) {
      const { list } = this.collectDetailSource
      if (i == 0 && t == 0) {
        return this.toast.fail('已经是第一个')
      } else if (i == list.length - 1 && t == 1) {
        return this.toast.fail('已经是最后一个')
      }
      Common.changeSort(i, t, this.collectDetailSource.list)
      this.collectDetailSource.list = this.collectDetailSource.list.map((item, index) => ({ ...item, colNo: index + 1 }))
    },
    tabChange(val) {
      this.listType = val.name
      this.getList()
    },
    // 创建、更新合辑
    async createColl() {
      const interFace = this.collectObj.isCreate ? API.createCollect : API.updateCollect
      this.collectObj = this.collectObj.isCreate ? { ...this.collectObj } : { id: this.collectObj.id, name: this.collectObj.name }
      this.$set(this.collectObj, 'isCreate', undefined)
      this.$set(this.collectObj, 'canUpdate', undefined)
      const [err,res] = await this.$await(interFace({ ...this.collectObj }))
      if(!err){
        this.toast.success('操作成功')
        this.getList()
        this.dialogVisible = false
      }
      this.collectDetailSource.list = []
      this.auditList = []
    },
    handleSelectionChange(val) {
      this.collectDetailSource.list = val
      this.collectObj.name = val[0]?.title ?? ''
      this.auditList = val
    },
    // 提交审核
    submitAudit: Fn.Confirm(function(type, id = '', taskId = '') {
      const promises = []
      let { auditList } = this
      if (type === 1) { // 表格内分别提审
        promises.push(API.allIn({ clipId: id, taskId }))
      } else { // 批量提审
        auditList = auditList.filter((item) => (item.status === 1 && (item.inStock === -1 || item.inStock === 2)))
        if (auditList.length === 0) return this.toast.fail('提审的数据有误或未选择')
        if (this.listType === '1') { // 独立素材提审
          auditList.forEach(item => {
            promises.push(API.allIn({ clipId: item.id, taskId: item.taskId }))
          })
        } else { // 合辑提审
          auditList.forEach(item => {
            promises.push(API.allIn({ colId: item.id }))
          })
        }
      }
      Promise.all(promises).then(res => {
        this.toast.success('操作成功')
        this.auditList = []
        this.getList()
      }).catch(err => console.log(err))
    }),
    sizeChange(val) {
      this.listQuery.limit = val.limit
      this.getList()
    },
    // 预览
    views(row) {
      if (row.meterialMaskUrl) {
        this.video.sourceUrl = row.meterialMaskUrl
      } else if (row.meterialUrl) {
        this.video.sourceUrl = row.meterialUrl
      } else {
        return this.toast.fail('暂时无法预览')
      }
      this.dialogView = true
    },
    sureView() {
      this.dialogView = false
      this.video.sourceUrl = undefined
    },
    // 删除
    handleDel: Fn.Confirm(async function(id) {
      const [err,res] = await this.$await(API.delClip({ id }))
      if(!err){
        this.toast.success('删除成功')
        this.getList()
      }
    }, '确定删除？'),

    Init() {
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 获取数据列表
    async getList() {
      if (this.listType === '1') {
        try {
          this.$set(this.materialSource.options, 'loading', true)
          const [err,res] = await this.$await(API.cliplist({ ...this.listQuery }))
          if(!err){
            this.materialSource.list = res.datas.list
            this.total = Number(res.datas.total)
          }
        } finally {
          this.$set(this.materialSource.options, 'loading', false)
        }
      } else {
        try {
          this.$set(this.collectSource.options, 'loading', true)
          const [err,res] = await this.$await(API.CollectList({ ...this.listQuery }))
          if(!err){
            this.collectSource.list = res.datas.list
            this.total = Number(res.datas.total)
          }
        } finally {
          this.$set(this.collectSource.options, 'loading', false)
        }
      }
      
    },
    // 创建合辑弹窗
    showDialog() {
      const { list } = this.collectDetailSource
      if (list.length == 0) return this.toast.fail('最少选择一条素材')
      this.collectDetailSource.list = list.map((item, index) => ({ ...item, colNo: Number(`${index + 1}`) }))
      this.collectObj.isCreate = true
      this.dialogVisible = true
    },

    async sureUpdate() {
      if (this.bind_title == '') return this.toast.fail('请输入标题')
      const [err,res] = await this.$await(API.updateClip({ id: this.clipId, title: this.bind_title }))
      if(!err){
        this.toast.success('更新成功')
        this.getList()
        this.dialogVisible = false
      }
    },
    handleEdit(id) {
      this.$router.push({ name: 'RadioMeterialClipEdit', query: { id }})
    }

  }
}
</script>

<style lang='scss' scoped>
  .clipdetail{

  }
</style>
<style>
  .views .el-dialog__body{
      padding:0px !important;
    }
</style>
